'use strict';

//引入必要文件
const fs = require('fs');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const HOST = '127.0.0.1';
const PORT = 5050;

// 返回html页面
class ResponseHtml {
    getHtml(reqPath, res) {
        this.path = path.join(__dirname, reqPath);
        fs.readFile(this.path, (err, data) => {
            if (err) {
                res.set({ 'Content-Type': 'text/html; charset=utf-8' });
                res.end('<h1 style="width:100%;margin:100px auto;text-align:center;">404-找不到页面</h1>');
            } else {
                res.set({ 'Content-Type': 'text/html; charset=utf-8' });
                res.end(data);
            }
        })
    }
}

const resHtml = new ResponseHtml();

app.use(bodyParser.urlencoded({ limit: '500mb', extended: true }));
app.use(bodyParser.json({ limit: '500mb' }));
app.use('/src/js', express.static('src/js'));
app.use('/src/css', express.static('src/css'));
app.use('/src/assets', express.static('src/assets'));
app.use('/upload/webDemo', express.static('upload/webDemo'));
app.use('/upload/pictures', express.static('upload/pictures'));
app.use('/static', express.static('static'));

app.get('/personalBlog', (req, res) => {
    resHtml.getHtml('/index.html', res);
})

//前端主页日志获取数据
app.get('/upload/articles', (req, res) => {
    let reqpath = path.join(__dirname, req.url, '/article.json');
    fs.readFile(reqpath, (err, data) => {
        if (err) {
            res.set({ 'Content-Type': 'text/html; charset=utf-8' });
            res.end('<h1 style="width:100%;margin:100px auto;text-align:center;">404-找不到页面</h1>');
        } else {
            res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
            res.end(data.toString());
        }
    })
})
app.get('/upload/webDemo', (req, res) => {
    let reqpath = path.join(__dirname, req.url, '/demo.json');
    fs.readFile(reqpath, (err, data) => {
        if (err) {
            res.set({ 'Content-Type': 'text/html; charset=utf-8' });
            res.end('<h1 style="width:100%;margin:100px auto;text-align:center;">404-找不到页面</h1>');
        } else {
            res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
            res.end(data.toString());
        }
    })
})

//前端日志页获取数据
app.get('/upload/articles/pages?*', (req, res) => {
    let reqpath = path.join(__dirname, '/upload/articles/article.json');
    let obj = JSON.parse(fs.readFileSync(reqpath));
    if (!obj) {
        console.error('读取错误！');
        res.send('no');
        return;
    }
    let newobj = {
        pages: Math.ceil(obj.infoArr.length / 6),
        arr: obj.infoArr.slice(req.query.start, req.query.end)
    }
    res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
    res.end(JSON.stringify(newobj));
})

//前端demo获取数据
app.get('/upload/webDemo/pages?*', (req, res) => {
    let reqpath = path.join(__dirname, '/upload/webDemo/demo.json');
    let obj = JSON.parse(fs.readFileSync(reqpath));
    if (!obj) {
        console.error('读取错误！');
        res.send('no');
        return;
    }
    let arr = obj.infoArr.slice(req.query.start, req.query.end);
    res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
    res.end(JSON.stringify(arr));
})

//前端获取图片url
app.get('/upload/pictures/pages?*', (req, res) => {
    fs.readFile(path.join(__dirname, '/upload/pictures/' + req.query.classN + '/pic_url.json'), (err, data) => {
        if (err) {
            console.error(err);
            res.end('no');
            return;
        }
        let obj = JSON.parse(data);
        let arr = obj.infoArr.slice(req.query.start, req.query.end);
        res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
        res.end(JSON.stringify(arr));

    })
})

//前端获取图片
app.get('/upload/pictures/files?*', (req, res) => {
    fs.readFile(path.join(__dirname, req.query.imgUrl), (err, data) => {
        if (err) {
            console.error(err);
            res.end('no');
            return;
        }
        res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
        res.end(data);
    })
})

//获取日志、demo、word的json数据
class ResponseFilesJson {
    getFiles(reqPath, fileName, res) {
        this.path = path.join(__dirname, reqPath, fileName);
        fs.readFile(this.path, (err, data) => {
            if (err) {
                res.set({ 'Content-Type': 'text/html; charset=utf-8' });
                res.end('<h1 style="width:100%;margin:100px auto;text-align:center;">404-找不到页面</h1>');
            } else {
                res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
                res.end(data.toString());
            }
        })
    }
}

const resJson = new ResponseFilesJson();

app.get('/get_article', (req, res) => {
    resJson.getFiles('/upload/articles/', 'article.json', res);
})
app.get('/get_demo', (req, res) => {
    resJson.getFiles('/upload/webDemo/', 'demo.json', res);
})
app.get('/get_word', (req, res) => {
    resJson.getFiles('/upload/word/', 'word.json', res);
})

//添加日志、demo、word的json数据
class CreateData {
    saveData(savePath, req, res, flag) {
        fs.readFile(path.join(__dirname, savePath), (err, data) => {
            if (err) {
                console.error(err);
            } else {
                let objData = JSON.parse(data);
                if (!flag) {
                    objData.infoArr.unshift(req.body);
                } else {
                    objData.infoArr.push(req.body);
                }
                fs.writeFile(path.join(__dirname, savePath), JSON.stringify(objData), (err) => {
                    if (err) {
                        console.error(err);
                        res.send('no');
                    } else {
                        res.send('ok');
                    }
                })
            }
        })
    }
}

const createData = new CreateData();

app.post('/create_article', (req, res) => {
    createData.saveData('/upload/articles/article.json', req, res);
})
app.post('/create_demo', (req, res) => {
    createData.saveData('/upload/webDemo/demo.json', req, res);
})
app.post('/create_word', (req, res) => {
    createData.saveData('/upload/word/word.json', req, res);
})

//删除日志、demo、word的json数据
class DeleteData {
    delData(delPath, req, res) {
        fs.readFile(path.join(__dirname, delPath), (err, data) => {
            if (err) {
                console.error(err);
                res.send('no');
            } else {
                let objData = JSON.parse(data);
                for (let i = 0; i < objData.infoArr.length; i++) {
                    if (req.body.id === objData.infoArr[i].id) {
                        objData.infoArr.splice(i, 1);
                        break;
                    }
                }
                fs.writeFile(path.join(__dirname, delPath), JSON.stringify(objData), (err) => {
                    if (err) {
                        console.error(err);
                        res.send('no');
                    } else {
                        res.send('ok');
                    }
                })
            }
        })
    }
}

const delleteData = new DeleteData();

app.post('/del_article', (req, res) => {
    delleteData.delData('/upload/articles/article.json', req, res);
})
app.post('/del_demo', (req, res) => {
    delleteData.delData('/upload/webDemo/demo.json', req, res);
})
app.post('/del_word', (req, res) => {
    delleteData.delData('/upload/word/word.json', req, res);
})

//获取图片
app.get('/get_pic_file?*', (req, res) => {
    let data = fs.readFileSync(path.join(__dirname, '/upload/pictures/' + req.query.classN + '/' + req.query.name + '.txt'));
    if (!data) {
        res.send('no');
        return;
    }
    res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
    res.send(data);
})

//获取图片url
app.get('/get_pic?*', (req, res) => {
    fs.readFile(path.join(__dirname, '/upload/pictures/' + req.query.classN + '/pic_url.json'), (err, data) => {
        if (err) {
            console.error(err);
            res.end('no');
            return;
        }
        res.set({ 'Content-Type': 'text/plain; charset=utf-8' });
        res.end(data.toString());
    })
})

//添加图片
class SubmitPic {
    sub(objData, res) {
        let savePath = path.join(__dirname, '/upload/pictures/' + objData.class + '/' + objData.name + '.txt');
        let readePath = path.join(__dirname, '/upload/pictures/' + objData.class + '/pic_url.json');
        let savePicUrl = {
            name: objData.name,
            class: objData.class,
            update: objData.update,
            imgUrl: '/upload/pictures/' + objData.class + '/' + objData.name + '.txt'
        }
        fs.writeFile(savePath, objData.imgUrlBase64, (err) => {
            if (err) {
                console.error(err);
                res.send('no');
                return;
            }
            let obj = JSON.parse(fs.readFileSync(readePath));
            obj.infoArr.unshift(savePicUrl);
            fs.writeFileSync(readePath, JSON.stringify(obj));
            res.send('ok');
        })
    }
}

const submitPic = new SubmitPic();

app.post('/submit_pic', (req, res) => {
    switch (req.body.class) {
        case 'view': submitPic.sub(req.body, res); break;
        case 'manga': submitPic.sub(req.body, res); break;
        case 'cate': submitPic.sub(req.body, res); break;
        case 'life': submitPic.sub(req.body, res); break;
    }
})

//删除图片
app.get('/del_pic?*', (req, res) => {
    let delPath = path.join(__dirname, '/upload/pictures/' + req.query.classN + '/' + req.query.name + '.txt');
    let readePath = path.join(__dirname, '/upload/pictures/' + req.query.classN + '/pic_url.json');
    fs.unlink(delPath, (err) => {
        if (err) {
            console.error(err);
            res.send('no');
            return;
        }
        let obj = JSON.parse(fs.readFileSync(readePath));
        for (let i = 0; i < obj.infoArr.length; i++) {
            if (req.query.name === obj.infoArr[i].name) {
                obj.infoArr.splice(i, 1);
            }
        }
        fs.writeFileSync(readePath, JSON.stringify(obj));
        res.send('ok');
    })
})

app.listen(PORT, () => {
    console.log(`回环测试服务启动：http://${HOST}:${PORT}/personalBlog`);
})
